package com.itboye.sunsun.shop.ui;

import java.util.ArrayList;
import java.util.List;

import com.itboye.sunsun.MainActivity;
import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.FenGuanGoodsAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.CarouselPictureBean;
import com.itboye.sunsun.beans.FenGuanGoodsBean;
import com.itboye.sunsun.beans.FenGuanGoodsBean.FenGuanItemBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.CarouselView;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.login.ui.LoginActivity;
import com.itboye.sunsun.luntan.TieZiDetailActivity;
import com.itboye.sunsun.message.ui.MessageActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.test.ImageUrls;
import com.itboye.sunsun.utils.DensityUtil;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsun.web.ui.WebActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView.ScaleType;
import android.widget.TextView.OnEditorActionListener;
import android.widget.PopupWindow;
import android.widget.ImageView;
import android.widget.TextView;
/**
 * 水族馆   宠物馆 钓具管等8个管的基类
 * @author young
 *
 */
public abstract class ShopActivity extends BaseActivity  {

	private XListView xlistview;
	private CarouselView carouselView;
 
	private View paixu;
	private View shaixuan;
	private View back;
	private View more;
	private TextView paixuTitle;
	
	private View sortSelect;
	private View shaixuanInput;
	
	private String parentId;
	private String childId; 
	private List<FenGuanItemBean> dataList=new ArrayList<FenGuanItemBean>();
	
	private FenGuanGoodsAdapter adapter;
	
	private String minCost;
	private String maxCost;
	
	private int pageNum=1;
	
	/**
	    * 综合排序
	    */
	 private static final String SORT_COMPREHENSIVE = "10";

	   /**
	    * 销量排序
	    */
	 private static final String SORT_SALE = "11";

	   /**
	    * 价格从低到高
	    */
	 private static final String SORT_PRICE_ASC = "12";

	   /**
	    * 价格从高到低
	    */
	 private static final String SORT_PRICE_DESC = "13";
	   
	 private String order=SORT_COMPREHENSIVE;
	 EditText sousuo;
	protected boolean isShow=true;
	protected boolean isShowShaixuan;
	protected void onCreate(android.os.Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_shop);
		showProgressDialog("数据正在加载中",true);
//		xlistview=(XListView) findViewById(R.id.xlistview);
		addCarouselView();
		
		xlistview.addHeaderView(addBannerView(xlistview));
		
		View v = getLayoutInflater().inflate(R.layout.item_shop_banner, null);
		paixu=v.findViewById(R.id.paixu);
		shaixuan=v.findViewById(R.id.shaixuan);
		paixuTitle=(TextView) v.findViewById(R.id.paixuTitle);
		sortSelect=v.findViewById(R.id.sortSelect);
		shaixuanInput=v.findViewById(R.id.shaixuanInput);
		sortSelect.findViewById(R.id.first).setOnClickListener(sortListenr);
		sortSelect.findViewById(R.id.second).setOnClickListener(sortListenr);
		sortSelect.findViewById(R.id.three).setOnClickListener(sortListenr);
		sortSelect.findViewById(R.id.four).setOnClickListener(sortListenr);
		
		xlistview.addHeaderView(v);
		
		 
		addAdapter();
		
		getCarouselViewData();
		
//		pullDown();
		xlistview.setPullRefreshEnable(true);
		xlistview.setPullLoadEnable(true);
		xlistview.setXListViewListener(new MyXlistenr());
		addListener();
		
		xlistview.setOnScrollListener(new MyScrollListenr());
		xlistview.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pullDown();
			}

			@Override
			public void onLoadMore() {
				pullUp();
			}

		});
	}

	private class MyScrollListenr implements OnScrollListener{

		 int lastPosi=-1;  
        
         boolean isFloating;  
         @Override  
         public void onScrollStateChanged(AbsListView view, int scrollState) {    }  
           
         @Override  
         public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {  
             
             if (lastPosi!=firstVisibleItem) {  
                 lastPosi=firstVisibleItem;  
                 
                 if (isFloating==false&&firstVisibleItem==3) {  
                     ViewGroup vg=(ViewGroup) xlistview.getChildAt(0);  
                     View floatView=vg.getChildAt(1);  
                     View textView=vg.getChildAt(0);  
                     textView.getLayoutParams().height=floatView.getHeight();  
                     vg.removeViewAt(1);  
                    ((ViewGroup) xlistview.getParent()).addView(floatView);  
                     isFloating=true;  
                 }  
                   
                 if (isFloating&&firstVisibleItem==2) {  
                     View floatView =((ViewGroup) xlistview.getParent()).getChildAt(1);  
                     ((ViewGroup) xlistview.getParent()).removeViewAt(1);  
                     ViewGroup vg=(ViewGroup) xlistview.getChildAt(1);  
                     vg.addView(floatView);  
                     isFloating=false;  
                 }  
                   
             }  
         }  
	}
	
	
	
	private void addListener() {
		// TODO Auto-generated method stub

		/*findViewById(R.id.soousuo).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(getApplicationContext(), ShopSouSuoActivity.class));
			}
		});*/
		
		sousuo.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					// 先隐藏键盘
					((InputMethodManager) sousuo.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
							.hideSoftInputFromWindow( getCurrentFocus().getWindowToken(),
									InputMethodManager.HIDE_NOT_ALWAYS);

				 
					pullDown();
					return true;
				}
				return false;
			}
		});
		paixu.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				shaixuanInput.setVisibility(View.GONE);
				if(isShowShaixuan==true){
					sortSelect.setVisibility(View.GONE);
					}else{
						sortSelect.setVisibility(View.VISIBLE);
					}
					isShowShaixuan=!isShowShaixuan;
				showAndHideCheck(order);
			}
		});
		
		shaixuan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sortSelect.setVisibility(View.GONE);
				if(isShow){
				shaixuanInput.setVisibility(View.VISIBLE);
				}	else{
					shaixuanInput.setVisibility(View.GONE);
					
				}
				((EditText)shaixuanInput.findViewById(R.id.minPrice)).setText(minCost);
				
				((EditText)shaixuanInput.findViewById(R.id.maxPrice)).setText(maxCost);
				
				isShow=!isShow;
			}
		});
		
		shaixuanInput.findViewById(R.id.priceOk).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {

				String min=((EditText)shaixuanInput.findViewById(R.id.minPrice)).getText().toString();
				
				String max=((EditText)shaixuanInput.findViewById(R.id.maxPrice)).getText().toString();
				
				if (TextUtils.isEmpty(min)) {
					minCost=null;
				}else{
					minCost=min;
				}
				
				if (TextUtils.isEmpty(max)) {
					maxCost=null;
				}else{
					maxCost=max;
				}
				
				pullDown();
				
			}
		});
		
		 more .setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				View pop=getLayoutInflater().inflate(R.layout.popupwindow_fenguan_right_corner, null);
				PopupWindow popupWindow=new PopupWindow(pop,ViewGroup.LayoutParams.WRAP_CONTENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
		        popupWindow.setFocusable(true);
		        popupWindow.setOutsideTouchable(true);
		        popupWindow.setBackgroundDrawable(new BitmapDrawable());
		        popupWindow.showAsDropDown(v);
		        pop.findViewById(R.id.shouye).setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(getApplicationContext(), MainActivity.class));
					}
				});
		        
		        pop.findViewById(R.id.xiaoxi).setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						LoginController.onShopMessageClick(ShopActivity.this, null);
						//startActivity(new Intent(getApplicationContext(), MessageActivity.class));
					}
				});
//				popupWindow.showAsDropDown(v, 0, 0);
				
			}
		});
		
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	protected void setParentIdAndChildId(String parent,String child) {
		this.parentId=parent;
		this.childId=child;
		pullDown();
		
	}
	private OnClickListener sortListenr =new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.first:
				order=SORT_COMPREHENSIVE;
				
				break;

			case R.id.second:
				order=SORT_PRICE_ASC;	
				break;
			case R.id.three:
				order=SORT_PRICE_DESC;
				break;
			case R.id.four:
				order=SORT_SALE;
				break;
			}
			showAndHideCheck(  order );
			sortSelect.setVisibility(View.GONE);
			pullDown();
		}
	};
	 
	private void showAndHideCheck(String order){
		
		if (SORT_COMPREHENSIVE.equals(order)) {
			paixuTitle.setText("综合排序");
			findViewById(R.id.iv1).setVisibility(View.VISIBLE);
		}else {
			findViewById(R.id.iv1).setVisibility(View.INVISIBLE);
		}
		
		if (SORT_PRICE_ASC.equals(order)) {
			paixuTitle.setText("价格从低到高");
			findViewById(R.id.iv2).setVisibility(View.VISIBLE);
		}else {
			findViewById(R.id.iv2).setVisibility(View.INVISIBLE);
		}
		
		if (SORT_PRICE_DESC.equals(order)) {
			paixuTitle.setText("价格从高到低");
			findViewById(R.id.iv3).setVisibility(View.VISIBLE);
		}else {
			findViewById(R.id.iv3).setVisibility(View.INVISIBLE);
		}
		
		if (SORT_SALE.equals(order)) {
			paixuTitle.setText("销量排序");
			findViewById(R.id.iv4).setVisibility(View.VISIBLE);
		}else {
			findViewById(R.id.iv4).setVisibility(View.INVISIBLE);
		}
		
		
	}
	class MyXlistenr implements IXListViewListener{

		@Override
		public void onRefresh() {
			pullDown();
		}

		@Override
		public void onLoadMore() {
			pullUp();
		}
		
	}
	protected   void pullDown(){
		String sou=sousuo.getText().toString();
		if(sou.equals("")){
		pageNum=1;
		MyJsonRequest.Builder<FenGuanGoodsBean> builder=new MyJsonRequest.Builder<FenGuanGoodsBean>()
				.apiVer("100")
				.typeKey("BY_Product_query")
				.param("cate_parent", parentId)
				.param("cate_id", childId)
				.param("page_no", ""+pageNum)
				.param("order", order)
				.requestListener(new XRequestListener<FenGuanGoodsBean>() {
					
					@Override
					public void onResponse(FenGuanGoodsBean arg0) {
						dataList.clear();
						if (arg0.getCount()>0) {
							dataList.addAll(arg0.getList());
							
						}
						adapter.setParentId(parentId);
						adapter.notifyDataSetChanged();
						pageNum++;
						xlistview.stopRefresh();
					}
				})
				.errorListener(new XErrorListener() {
					
					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						xlistview.stopRefresh();
					}
				});
			 
		
		if (!TextUtils.isEmpty(minCost)) {
			builder.param("min_cost", minCost);
		}
		if (!TextUtils.isEmpty(maxCost)) {
			builder.param("max_cost", maxCost);
		}
		MyJsonRequest< FenGuanGoodsBean >request=builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
		}else {
			
			pageNum=1;
			MyJsonRequest.Builder<FenGuanGoodsBean> builder=new MyJsonRequest.Builder<FenGuanGoodsBean>()
					.apiVer("100")
					.typeKey("BY_Product_query")
					.param("name",sou)
					.param("cate_parent", parentId)
					.param("cate_id", childId)
					.param("page_no", ""+pageNum)
					.param("order", order)
					.requestListener(new XRequestListener<FenGuanGoodsBean>() {
						
						@Override
						public void onResponse(FenGuanGoodsBean arg0) {
							dataList.clear();
							if (arg0.getCount()>0) {
								dataList.addAll(arg0.getList());
								
							}
							adapter.setParentId(parentId);
							adapter.notifyDataSetChanged();
							pageNum++;
							xlistview.stopRefresh();
							
						}
					})
					.errorListener(new XErrorListener() {
						
						@Override
						public void onErrorResponse(Exception exception, int code, String msg) {
							xlistview.stopRefresh();
						}
					});
				 
			
			if (!TextUtils.isEmpty(minCost)) {
				builder.param("min_cost", minCost);
			}
			if (!TextUtils.isEmpty(maxCost)) {
				builder.param("max_cost", maxCost);
			}
			MyJsonRequest< FenGuanGoodsBean >request=builder.build();
			HttpRequest.getDefaultRequestQueue().add(request);
			
		}
	}

	protected void pullUp() {
		MyJsonRequest.Builder<FenGuanGoodsBean>builder=new MyJsonRequest.Builder<FenGuanGoodsBean>()
				.apiVer("100")
				.typeKey("BY_Product_query")
				.param("cate_parent", parentId)
				.param("cate_id", childId)
				.param("page_no", ""+pageNum)
				.param("order", SORT_COMPREHENSIVE)
				.requestListener(new XRequestListener<FenGuanGoodsBean>() {
					
					@Override
					public void onResponse(FenGuanGoodsBean arg0) {
						if (arg0.getList()!=null) {
							dataList.addAll(arg0.getList());
						
							adapter.notifyDataSetChanged();
							pageNum++;
						}
						xlistview.stopLoadMore();
					}
				})
				.errorListener(new XErrorListener() {
					
					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						xlistview.stopLoadMore();
					}
				});
				 
		
		if (!TextUtils.isEmpty(minCost)) {
			builder.param("min_cost", minCost);
		}
		if (!TextUtils.isEmpty(maxCost)) {
			builder.param("max_cost", maxCost);
		}
		MyJsonRequest<FenGuanGoodsBean>request=builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}
	
	
	
	
	
	
	
	
	
	
	private void getCarouselViewData() {

		MyJsonRequest<List<CarouselPictureBean>>request=new MyJsonRequest.Builder<List<CarouselPictureBean>>()
				.apiVer("100")
				.typeKey("BY_Picture_getURL")
				.param("position", onGetBannerId())
				.requestListener(new XRequestListener<List<CarouselPictureBean>>() {
					
					@Override
					public void onResponse(List<CarouselPictureBean> arg0) {
						List<ImageView>bmps=new ArrayList<ImageView>();
						for (CarouselPictureBean pictureBean : arg0) {
							ImageView imageView=new ImageView(App.ctx);
							
							 imageView.setScaleType(ScaleType.CENTER_CROP);
							 imageView.setTag(pictureBean);
							 XImageLoader.load(pictureBean.getImgUrl(), imageView);
							bmps.add( imageView);
							imageView.setOnClickListener(new OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									CarouselPictureBean bean = (CarouselPictureBean) v
											.getTag();
									// 轮播图跳转类型 6070 链接 6071
									// app商品 6072 app帖子
									if ((NetPublicConstant.secondUrl+"/Webview/Game/index").equals(bean
											.getUrl())) {
										String uid = SPUtils.get(ShopActivity.this, null,
												SPContants.USER_ID, "") + "";
										if (uid == null) {
											Intent intent = new Intent(ShopActivity.this,
													LoginActivity.class);
											startActivity(intent);
										} else {
											Intent intent = new Intent(App.ctx, WebActivity.class);
											intent.putExtra("title", "抽奖");
											intent.putExtra(
													"url",
													bean.getUrl()
															+ "?uid="
															+ uid
															+ "&psw="
															+ SPUtils.get(ShopActivity.this,
																	null, SPContants.PASSWORD, "") + "");
											startActivity(intent);
										}
										return ;
									}
									if ("6070".equals(bean
											.getUrlType())) {

										if (!bean.getUrl()
												.equals("")) {

											Intent intent = new Intent(
													App.ctx,
													WebActivity.class);
											// intent.putExtra("title",
											// "商品详情");
											intent.putExtra(
													"url",
													bean.getUrl());
											startActivity(intent);
										}
									} else if ("6071".equals(bean
											.getUrlType())) {
										Intent intent = new Intent(
												App.ctx,
												GoodDetailActivity.class);
										intent.putExtra("what",
												bean.getUrl());
										startActivity(intent);
									} else if ("6072".equals(bean
											.getUrlType())) {

										startActivity(new Intent(
												App.ctx,
												TieZiDetailActivity.class));

									}
								}
							});
							

						}
					 
						
						carouselView.setImageBitmaps(bmps);
						try {
							
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				})
				.errorListener(new XErrorListener() {
					
					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						try {
							
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				})
				.build();
		HttpRequest.getDefaultRequestQueue().add(request);
		
		
	}
	protected abstract View addBannerView(ViewGroup parent ) ;
	
	protected abstract String onGetBannerId() ;
	

	private void addAdapter() {
		adapter=new FenGuanGoodsAdapter(dataList,this);
		xlistview.setAdapter(adapter);

	}
  

	private void addCarouselView() {
		// TODO Auto-generated method stub
		carouselView = new CarouselView(getApplicationContext());
		AbsListView.LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(200));
		carouselView.setLayoutParams(layoutParams);
		xlistview.addHeaderView(carouselView);

	}

	 
}
